import { baseUrl } from './env'
import qs from 'qs'
import axios from 'axios'
import { getCookie } from '@/utils/storage'
import router from '../router'
import { Indicator } from 'mint-ui'

function createURL (url, params) {
  url += '?'
  for (let item in params) {
    url += `${item}=${params[item]}&`
  }
  return url.substr(0, url.length - 1)
}

axios.defaults.timeout = 30000
axios.defaults.baseURL = baseUrl
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
axios.defaults.headers.common['Content-Type'] = 'application/json'

// 请求设置
axios.interceptors.request.use(config => {
  if (config.method === 'post' && config.stringify) {
    config.data = qs.stringify(config.data)
  }
  config.headers.token = getCookie('token') || ''
  Indicator.open({ spinnerType: 'fading-circle' })
  return config
}, error => Promise.reject(error))

// 响应设置
axios.interceptors.response.use(res => {
  const resStatus = res.data.status
  if (resStatus === -1) {
    router.replace({ path: '/login' })
  }
  Indicator.close()
  return res.data
}, error => {
  Indicator.close()
  Promise.reject(error)
})

const get = (url, params, showLoading) => {
  url = createURL(url, params)
  return axios.get(url, { showLoading })
}

export {
  get
}